package com.xuan.webfinally.utils;

import javax.imageio.IIOException;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;


/**
 * @ServerEndpoint 注解是一个类层次的注解，它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */
@ServerEndpoint("/socket")
public class Main {
    //    记录在线连接数量
    private static int Onlinecount = 0;
    //    用来存放客户端对应的socket对象
    private static CopyOnWriteArrayList<Main> webSocketSet = new CopyOnWriteArrayList<Main>();
    private Session session;  //通过这个给客户端发送数据
    @OnOpen
    public void onOpen(Session session)
    {
        this.session = session;
        webSocketSet.add(this);
        addOnlinecount();
        System.out.println("有新连接加入！当前在线人数为" + getOnlinecount());
    }
    @OnClose
    public void close()
    {
        webSocketSet.remove(this); //congset中删除
        subOnlinecount();
        System.out.println("有连接关闭！当前在线人数为" + getOnlinecount());
    }

    private static synchronized void subOnlinecount() {
        Onlinecount--;
    }
    @OnMessage
    public void onMessage(String message)
    {
        System.out.println("来自客户端的消息:" + message);
//      群发消息
        for (Main item : webSocketSet) {
            try {
                item.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
    }
    @OnError
    public void Onerror(Session session, Throwable error)
    {
        System.out.println("发生错误");
        error.printStackTrace();
    }
    public void sendMessage(String message) throws IOException{
        this.session.getBasicRemote().sendText(message);

    }

    public static synchronized void addOnlinecount()
    {
        Main.Onlinecount++;
    }
    public static synchronized int getOnlinecount()
    {
        return Onlinecount;
    }
}
